<template>
  <div class="purchase-add-container">
    <!-- 操作按钮区 -->
    <div class="action-bar">
      <el-button type="primary" @click="handleSave">保存</el-button>
      <el-button @click="handleCancel">撤销</el-button>
    </div>
    <!-- 表单区 -->
    <el-card class="form-card" shadow="never">
      <el-form :model="form" label-width="90px" class="purchase-form">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="采购员" required>
              <el-select v-model="form.PurchaserId" placeholder="请选择采购员" filterable>
                <el-option v-for="item in purchaserList" :key="item.UserId" :label="item.UserName" :value="item.UserId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="采购日期" required>
              <el-date-picker v-model="form.PurchaseDate" type="date" placeholder="请选择采购日期" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="羊只类型" required>
              <el-select v-model="form.SheepTypeId" placeholder="请选择羊只类型" filterable>
                <el-option v-for="item in sheepTypeList" :key="item.Id" :label="item.TypeName || item.Name" :value="item.Id" />
              </el-select>
            </el-form-item>
          </el-col>
        
        </el-row>
        <el-row :gutter="20">
          
          <el-col :span="6">
            <el-form-item label="类别">
              <el-input v-model="form.Category" placeholder="采购单" disabled/>
            </el-form-item>
          </el-col>
          
          <el-col :span="6">
            <el-form-item label="单据单元">
              <el-select v-model="form.AccountingUnitId" placeholder="默认">
                <el-option label="默认" :value="0" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="单据号">
              <el-input v-model="form.BillNo" placeholder="--" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="流水号">
              <el-input v-model="form.SerialNo" placeholder="--" />
            </el-form-item>
          </el-col>
        </el-row>
        
      </el-form>
    </el-card>
    <!-- 表格区 -->
    <el-card class="table-card" shadow="never">
      <el-table :data="form.details" border stripe style="width: 100%">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="EarNumber" label="耳号" width="120" align="center">
          
            <el-select v-model="form.EarNumber" placeholder="请选择耳号" size="small">
              <el-option v-for="item in earNumberOptions" :key="item" :label="item" :value="item" />
            </el-select>
         
        </el-table-column>
        
        <el-table-column prop="PenName" label="栋舍" width="100" align="center">
       
            <el-select v-model="form.PenId" placeholder="请选择栋舍" size="small">
              <el-option v-for="item in penList" :key="item.House_typeId" :label="item.DongsheName" :value="item.House_typeId" />
            </el-select>
          
        </el-table-column>
        <el-table-column prop="Gender" label="性别" width="80" align="center">
          
            <el-select v-model="form.Gender" placeholder="请选择" size="small">
              <el-option label="公" value="公" />
              <el-option label="母" value="母" />
            </el-select>
     
        </el-table-column>
      
        <el-table-column prop="Tag" label="标签" width="100" align="center">
         
            <el-input v-model="form.Tag" placeholder="标签" size="small" />
         
        </el-table-column>
        <el-table-column prop="Unit" label="计量单位" width="100" align="center">
         
            <el-input v-model="form.Unit" placeholder="单位" size="small" />
          
        </el-table-column>
        <el-table-column prop="Quantity" label="入库数量" width="100" align="center">
          
            <el-input-number v-model="form.Quantity" :min="0" size="small" />
          
        </el-table-column>
        <el-table-column prop="UnitPrice" label="只均单价(元)" width="120" align="center">
       
            <el-input-number v-model="form.UnitPrice" :min="0" size="small" />
          
        </el-table-column>
        <el-table-column prop="Amount" label="金额(元)" width="100" align="center" />
        <el-table-column prop="Discount" label="折扣(元)" width="100" align="center">
          
            <el-input-number v-model="form.Discount" :min="0" size="small" />
        
        </el-table-column>
        <el-table-column prop="Adjustment" label="调整金额(元)" width="120" align="center">
          
            <el-input-number v-model="form.Adjustment" :min="0" size="small" />
         
        </el-table-column>
        <el-table-column prop="FinalAmount" label="结算金额(元)" width="120" align="center" />
        <el-table-column prop="TotalWeight" label="总重量(公斤)" width="120" align="center">
          <template #default="scope">
            <el-input-number v-model="scope.row.TotalWeight" :min="0" size="small" />
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="80" align="center">
          <template #default="scope">
            <el-button link type="danger" size="small" @click="removeDetail(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="table-actions">
        <el-button type="primary" @click="addDetail" icon="el-icon-plus">新增行</el-button>
      </div>
    </el-card>
    <!-- 合计区 -->
    <div class="summary-section">
      <span>合计：</span>
      <span>数量：{{ totalQuantity }}</span>
      <span>金额：{{ totalAmount.toFixed(2) }}</span>
      <span>结算金额：{{ totalFinalAmount.toFixed(2) }}</span>
      <span>总重量：{{ totalWeight.toFixed(2) }}</span>
    </div>
    <!-- 备注区 -->
    <el-card class="remark-card" shadow="never">
      <el-form-item label="备注">
        <el-input v-model="form.Remark" type="textarea" placeholder="请填写备注信息" />
      </el-form-item>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { Sheep_BreedingWrite, serviceRead, Sheep_BreedingRead } from '@/utils/Interceptors';
import { useRoute, useRouter } from 'vue-router'
const route = useRoute()
const router = useRouter()

const purchaserList = ref<any[]>([]); // 采购员下拉
const sheepTypeList = ref<any[]>([]); // 羊只类型下拉
const supplierList = ref<any[]>([]); // 供应商下拉
const warehouseList = ref<any[]>([]); // 仓库下拉
const penList = ref<any[]>([]); // 栋舍下拉
const batchList = ref<any[]>([])
const BatchNumber = [
    '空胎', '其他', '老龄', '屡配不孕', '习惯性流产', '子宫脱', '子宫炎', '肥胖', '消瘦', '精液质量差', '拒配', '无乳'
]
const form = reactive({
  PurchaserId: '',
  PurchaseDate: '',
  SheepTypeId: '',
  SupplierId: '',
  WarehouseId: '',
  Category: '采购单',
  Summary: '外购转入',
  AccountingUnitId: 0,
  BillNo: '',
  SerialNo: '',
  Remark: '',
  EarNumber: '', // 新增批次号
  PenId: '',
  PenName: '',
  Gender: '',
  SheepTypeName: '',
  Tag: '',
  Unit: '',
  Quantity: 0,
  UnitPrice: 0,
  Amount: 0,
  Discount: 0,
  Adjustment: 0,
  FinalAmount: 0,
  TotalWeight: 0,
  details: [
    {
      EarNumber: '',
      BatchNumber: '',
      PenId: '',
      PenName: '',
      Gender: '',
      SheepTypeName: '',
      Tag: '',
      Unit: '',
      Quantity: 0,
      UnitPrice: 0,
      Amount: 0,
      Discount: 0,
      Adjustment: 0,
      FinalAmount: 0,
      TotalWeight: 0
    }
  ]
});

const earNumberOptions = ref<string[]>([]);
const fetchEarNumbers = () => {
  Sheep_BreedingRead.get('/api/EliminationInfo/GetSheepFilesIDEarNumber').then(res => {
    earNumberOptions.value = (res.data.data || []).map((item: any) => item.Name);
  });
};

const addDetail = () => {
  form.details.push({
    EarNumber: '',
    BatchNumber: '',
    PenId: '',
    PenName: '',
    Gender: '',
    SheepTypeName: '',
    Tag: '',
    Unit: '',
    Quantity: 0,
    UnitPrice: 0,
    Amount: 0,
    Discount: 0,
    Adjustment: 0,
    FinalAmount: 0,
    TotalWeight: 0
  });
};
const removeDetail = (index: number) => {
  form.details.splice(index, 1);
};

const totalQuantity = computed(() => form.details.reduce((sum, d) => sum + Number(d.Quantity || 0), 0));
const totalAmount = computed(() => form.details.reduce((sum, d) => sum + Number(d.Amount || 0), 0));
const totalFinalAmount = computed(() => form.details.reduce((sum, d) => sum + Number(d.FinalAmount || 0), 0));
const totalWeight = computed(() => form.details.reduce((sum, d) => sum + Number(d.TotalWeight || 0), 0));

const handleSave = async () => {
  try {
    let res
    if (route.query.id) {
      // 修改时用PUT方法，接口为/api/SheepPurchase/update，必须有Id字段
      res = await Sheep_BreedingWrite.put('/api/SheepPurchase/update', form)
    } else {
      res = await Sheep_BreedingWrite.post('/api/SheepPurchase/add', form)
    }
    if (res.data && res.data.code === 200) {
      ElMessage.success(res.data.msg || '保存成功')
      // 可选：跳转回采购列表
      router.push({ name: 'PurchaseView' })
    } else {
      ElMessage.error(res.data.msg || '保存失败')
    }
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.msg || '请求失败')
  }
}
const handleCancel = () => {
  // TODO: 撤销逻辑
  ElMessage.info('已撤销（示例）');
};

// 获取羊只类型
const fetchSheepTypeList = () => {
  Sheep_BreedingWrite.get('/api/SheepType/List/list').then(res => {
    console.log('羊只类型接口返回', res.data);
    if (res.data && res.data.code === 200) {
      sheepTypeList.value = res.data.data || []
    } else {
      sheepTypeList.value = []
    }
  })
}
// 获取采购员（不带参数）
const fetchPurchaserList = () => {
  serviceRead.get('/api/User/SraechUser').then(res => {
    purchaserList.value = res.data.PageData || res.data.data || []
  })
}

// 获取栋舍列表
const fetchPenList = () => {
  Sheep_BreedingWrite.get('/api/Pen/List').then(res => {
    if (res.data && res.data.code === 200) {
      penList.value = res.data.data || []
    } else {
      penList.value = []
    }
  })
}

const fetchBatchList = () => {
  Sheep_BreedingWrite.get('/api/SheepPurchase/BatchList').then(res => {
    batchList.value = res.data.data || []
  })
}

// 监听羊只类型变化，自动刷新采购员下拉
watch(() => form.SheepTypeId, (val) => {
  if (val) {
    // 如果采购员和羊只类型有关，这里需要根据羊只类型过滤
    // 例如，假设有一个接口 /api/User/SraechUser?SheepTypeId=123 返回该类型下的采购员
    // 那么你需要这样调用：
    // serviceRead.get('/api/User/SraechUser', { params: { SheepTypeId: val } }).then(res => {
    //   purchaserList.value = res.data.PageData || res.data.data || []
    // })
  } else {
    // 如果采购员和羊只类型无关，直接请求所有采购员
    fetchPurchaserList()
  }
})

onMounted(() => {
  if (route.query.id) {
    Sheep_BreedingWrite.get(`/api/SheepPurchase/detail/${route.query.id}`).then(res => {
      if (res.data && res.data.code === 200) {
        // 主表字段
        Object.assign(form, res.data.data)
        // 明细字段
        if (res.data.data.details) {
          form.details = res.data.data.details
        }
      }
    })
  }
  fetchSheepTypeList()
  fetchPurchaserList()
  fetchPenList()
  fetchBatchList()
  fetchEarNumbers();
  // 其他下拉数据可在此处拉取
});
</script>

<style scoped>
.purchase-add-container {
  min-height: 100vh;
  background: #f7f8fa;
  padding: 24px;
}
.action-bar {
  margin-bottom: 16px;
}
.form-card {
  margin-bottom: 18px;
}
.purchase-form {
  padding: 12px 0;
}
.table-card {
  margin-bottom: 12px;
}
.table-actions {
  margin-top: 8px;
}
.summary-section {
  margin: 12px 0 18px 0;
  font-size: 16px;
  font-weight: 500;
  color: #333;
  display: flex;
  gap: 32px;
}
.remark-card {
  margin-top: 12px;
}
</style> 